package com.banzhi.shop.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.activity.GroupOrderDetailsActivity;
import com.banzhi.shop.activity.GroupingDetailsActivity;
import com.banzhi.shop.activity.MyGroupActivity3;
import com.banzhi.shop.activity.RefundRequestActivity;
import com.banzhi.shop.activity.RefundRequestActivity2;
import com.banzhi.shop.activity.ShouhouOrderInfoActivity;
import com.banzhi.shop.activity.ShouhouOrderInfoActivity2;
import com.banzhi.shop.activity.ShouhouShenqingActivity;
import com.banzhi.shop.adapter.MyGroupingAdapter;
import com.banzhi.shop.data.GroupShareBean;
import com.banzhi.shop.data.MyGroupingData;
import com.banzhi.shop.data.PinTuanBean;
import com.banzhi.shop.entity.RefundRequest.Refund_Data;
import com.banzhi.shop.model.CallBack.ConfirmReceiptCallBack;
import com.banzhi.shop.model.CallBack.GroupRefundRequestCallBack;
import com.banzhi.shop.model.CallBack.GroupShareCallBack;
import com.banzhi.shop.model.CallBack.PinTuanCallBack;
import com.banzhi.shop.model.Impl.ConfirmReceiptImpl;
import com.banzhi.shop.model.Impl.GroupRefundRequestImpl;
import com.banzhi.shop.model.Impl.GroupShareImpl;
import com.banzhi.shop.model.Impl.MyGroupingImpl;
import com.banzhi.shop.model.Impl.PinTuanImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.moor.imkf.ormlite.logger.Log;
import com.moor.imkf.ormlite.stmt.query.In;
import com.nostra13.universalimageloader.utils.L;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;

/**
 * Created by Administrator on 2018/8/1.
 */


public class MyGroupingFragments2 extends Fragment implements  MyGroupingAdapter.OnItemClickListener, PinTuanCallBack, GroupShareCallBack, ConfirmReceiptCallBack, GroupRefundRequestCallBack {
    private SmartRefreshLayout mSmartRefreshLayout;
    private RecyclerView mRecyclerView;
    private MyGroupingImpl mModel;
    private String mType;
    private int page = 1;
    // private List<MyGroupingBean> mMyGroupingBean;
    private List<PinTuanBean> mMyGroupingBeans = new ArrayList<>();
    private RelativeLayout mRlNoData;
    //   private TextView mTvNoData;
    private Button mButton;
    private MyGroupingAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private List<MyGroupingData.MyGroupingBean> mMyGroupingBean;
    private List<PinTuanBean> mPinTuanBeans;
    private PinTuanImpl mPinTuan;
    private GroupShareImpl mGroupShareModel;
    private GroupShareBean mGroupShareBean;
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private TextView mTvDes;
    private ConfirmReceiptImpl mConfirmReceiptModel;
   // private String mOid;
    private PinTuanBean mPinTuanBean;
    private GroupRefundRequestImpl mRefundRequestModel;
    private int position;
    private FragmentActivity mActivity;
    private FragmentActivity mFragmentActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragments_my_grouping2, container, false);
        ShareSDK.initSDK(getActivity(), "1dc05ab16fd6c");
        initView(view);
        //获取传过来的fragment的id;
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            mType = bundle.getString("type");
        }
     /*   mFragmentActivity = getActivity();
        if (mFragmentActivity instanceof MyGroupActivity3) {
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("TT", "1");
        editor.apply();
        }*/

        //拼团接口
        mPinTuan = new PinTuanImpl();
        mPinTuan.getData(mType + "", page + "", 20 + "", this);
        //分享接口
        mGroupShareModel = new GroupShareImpl();
        mConfirmReceiptModel = new ConfirmReceiptImpl();
        mRefundRequestModel = new GroupRefundRequestImpl();
        return view;


    }

    private void initView(View view) {
        mSmartRefreshLayout = (SmartRefreshLayout) view.findViewById(R.id.smart_refresh_layout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        mRlNoData = (RelativeLayout) view.findViewById(R.id.rl_nodata);
        mTvDes = (TextView) view.findViewById(R.id.tv_description);
    }
    //成功获取拼团数据
    @Override
    public void ongetDataSuccess(Object object) {
        mSmartRefreshLayout.finishRefresh();
        mPinTuanBeans = (List<PinTuanBean>) object;
        if (page == 1) {
            mMyGroupingBeans.clear();
        } else {
            if (mPinTuanBeans.size() == 0) {
                return;
            }
        }
        mMyGroupingBeans.addAll(mPinTuanBeans);


    //    LogUtils.e("size", mMyGroupingBeans.size() + "");
        if (mMyGroupingBeans.size() == 0) {
            mRlNoData.setVisibility(View.VISIBLE);
            if ("0".equals(mType)) {
                mTvDes.setText("亲，你还没有发起过拼团哦~");
            } else if ("1".equals(mType)) {
                mTvDes.setText("亲，你还没有拼团中的商品~");
            } else if ("2".equals(mType)) {
                mTvDes.setText("亲，你还没有拼团成功哦~");
            } else if ("3".equals(mType)) {
                mTvDes.setText("亲，你还没有拼团失败呢~");
            } else if ("4".equals(mType)) {
                mTvDes.setText("亲，你还没有拼团售后呢~");
            }
        } else {
            mRlNoData.setVisibility(View.GONE);
        }
        showView();

    }
    private void showView() {
        mAdapter = new MyGroupingAdapter(mMyGroupingBeans);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        setRefreshListener();
    }
    private void setRefreshListener() {

        //设置 Footer 为 经典样式
        mSmartRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        mSmartRefreshLayout.setHeaderHeight(60);//Header标准高度（显示下拉高度>=标准高度 触发刷新）
        mSmartRefreshLayout.setPrimaryColorsId(R.color.backgroudColor, android.R.color.white);
        mSmartRefreshLayout.setFooterHeight(60);//Footer标准高度（显示上拉高度>=标准高度 触发加载）

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPinTuan.getData(mType + "", page + "", 20 + "", MyGroupingFragments2.this);
                //刷新视图
                mAdapter.notifyDataSetChanged();
                mSmartRefreshLayout.finishRefresh();
            }
        });
        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                mPinTuan.getData(mType + "", page + "", 20 + "", MyGroupingFragments2.this);
                int count = mAdapter.getItemCount();
                int size = mPinTuanBeans.size();
                if (count == size) {
                    // Toast.makeText(getContext(), "数据以空", Toast.LENGTH_SHORT).show();
                }
                //当前试图总条目+20就是 一次加载20条目
                if (count + 20 < size) {
                    for (int i = count; i < (count + 20); i++) {
                        mMyGroupingBeans.add(mPinTuanBeans.get(i));
                    }
                } else {
                    for (int i = count; i < size; i++) {
                        mMyGroupingBeans.add(mPinTuanBeans.get(i));
                    }
                }
                 mAdapter.notifyDataSetChanged();
                mSmartRefreshLayout.finishLoadmore();


            }
        });
    }
    public static MyGroupingFragments2 newInstance(String type) {
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        MyGroupingFragments2 myGroupingFragments = new MyGroupingFragments2();
        myGroupingFragments.setArguments(bundle);
        return myGroupingFragments;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (view.getId()) {
            //查看订单详情
            case R.id.bt1:
                Intent intent = new Intent(getActivity(), GroupOrderDetailsActivity.class);
                intent.putExtra("goodid", mMyGroupingBeans.get(position).getGoodid());
                intent.putExtra("teamid", mMyGroupingBeans.get(position).getTeamid());
                //   intent.putExtra("type",mMyGroupingBeans.get(position).getType());
                startActivity(intent);
                break;

            //邀请好友
            case R.id.bt2:
                mPinTuanBean = mMyGroupingBeans.get(position);
                showSharePopupwindow(mPinTuanBean);
                break;
            case R.id.bt4:   //申请售后
                PinTuanBean pinTuanBean2 = mMyGroupingBeans.get(position);
                mRefundRequestModel.getData(pinTuanBean2.getOid(),this);
                MyGroupingFragments2.this.position = position;

                break;
            case R.id.bt6:   //确认收货
                PinTuanBean pinTuanBean3 = mMyGroupingBeans.get(position);
                showConfirmReceiptPopupwindow(pinTuanBean3);
                break;
            case R.id.bt7: //售后详情
                PinTuanBean pinTuanBean4 = mMyGroupingBeans.get(position);
                Intent intent2 = new Intent(getActivity(), ShouhouOrderInfoActivity2.class);
                intent2.putExtra("id",pinTuanBean4.getRefundid()+"");
                intent2.putExtra("oid",pinTuanBean4.getOid()+"");
                startActivity(intent2);
                break;
            case R.id.bt8:   //确认收货
                PinTuanBean pinTuanBean5 = mMyGroupingBeans.get(position);
                Intent intent3 = new Intent(getActivity(), ShouhouOrderInfoActivity2.class);
                intent3.putExtra("id",pinTuanBean5.getRefundid()+"");
                intent3.putExtra("oid",pinTuanBean5.getOid()+"");
                startActivity(intent3);
                break;
                //条目点击事件
         case R.id.ll_item:
             if ("1".equals(mMyGroupingBeans.get(position).getGoodstatus())) {
                 Intent intent1 = new Intent(getActivity(), GroupingDetailsActivity.class);
                 intent1.putExtra("id",mMyGroupingBeans.get(position).getGid());
                 startActivity(intent1);
             }else {
                 ToastUtils.makeToastShort("该拼团商品已经下架。");
             }
        /*     Intent intent1 = new Intent(getActivity(), GroupingDetailsActivity.class);
             intent1.putExtra("id",mMyGroupingBeans.get(position).getGid());
             startActivity(intent1);*/

             break;
        }
    }



    private void showConfirmReceiptPopupwindow(final PinTuanBean pinTuanBean) {
        //设置contentView
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popupwindow_queren_shouhuo, null);
        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int height = getContext().getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(contentView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvtrue = (TextView) contentView.findViewById(R.id.tv_true);
        RelativeLayout rl = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tvtrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mConfirmReceiptModel.confirmReceiptData( pinTuanBean.getOid() ,MyGroupingFragments2.this);
               // setRefreshListener();
                popWindow.dismiss();
            }
        });
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    private void showSharePopupwindow(final PinTuanBean bean) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        TextView mMake_money = (TextView) contentView.findViewById(R.id.make_money);
        TextView mYuan = (TextView) contentView.findViewById(R.id.yuan);
        TextView mYuan2 = (TextView) contentView.findViewById(R.id.yuan2);

        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (bean != null) {
            if ("1".equals(bean.getType())) {
                tvprice.setText(NumberUtils.DecimalFormat(bean.getGroupsprice()));
                tvpricetwo.setText(NumberUtils.DecimalFormat(bean.getGroupsprice()));

            } else {
                mMake_money.setVisibility(View.GONE);
                tvprice.setText("免费得商品");
                tvpricetwo.setText("免费得到此商品");
                mYuan.setVisibility(View.GONE);
                mYuan2.setVisibility(View.GONE);

            }

            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
                        //  wxmodel.getData(goodsdata.getId(), null, LIANJIE, GroupOrderDetailsActivity.this);
                        mGroupShareModel.getGroupShareData(bean.getOid(), LIANJIE, MyGroupingFragments2.this);
                    } else {
                        ShareUtils.copyLianjie(getActivity(), wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
                        // wxmodel.getData(goodsdata.getId(), null, ERWEIMA, GroupOrderDetailsActivity.this);
                        mGroupShareModel.getGroupShareData(bean.getOid(), ERWEIMA, MyGroupingFragments2.this);
                        LogUtils.e("Oid",bean.getOid());
                    } else {
                        ShareUtils.ereima4(getActivity(), mGroupShareBean.getSharetitle(), mGroupShareBean.getGroupsprice(), null, null, null, bean.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        //    type = 1;
                        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
                        //  wxmodel.getData(goodsdata.getId(), null, WEIXINHAOYOU, GroupOrderDetailsActivity.this);
                        mGroupShareModel.getGroupShareData(bean.getOid(), WEIXINHAOYOU, MyGroupingFragments2.this);
                    } else {
                        ShareUtils.wxshare(mGroupShareBean.getSharetitle(), mGroupShareBean.getShareicon(), mGroupShareBean.getSharedesc(), wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
                        //   wxmodel.getData(goodsdata.getId(), null, PENGYOUQUAN, GroupOrderDetailsActivity.this);
                        mGroupShareModel.getGroupShareData(bean.getOid(), PENGYOUQUAN, MyGroupingFragments2.this);
                    } else {
                        ShareUtils.wxPengyouquan(mGroupShareBean.getSharetitle(), mGroupShareBean.getShareicon(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


    }

    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
        mSmartRefreshLayout.finishRefresh();
    }

    @Override
    public void ongetGroupShareDataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        mGroupShareBean = (GroupShareBean) object;
        wxURL = mGroupShareBean.getSharelink();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(getActivity(), wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima4(getActivity(), mGroupShareBean.getSharetitle(), mGroupShareBean.getGroupsprice(), null, null, null, mGroupShareBean.getShareicon(), wxURL);
        } else if (num == WEIXINHAOYOU) {
            ShareUtils.wxshare(mGroupShareBean.getSharetitle(), mGroupShareBean.getShareicon(), mGroupShareBean.getSharedesc(), wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(mGroupShareBean.getSharetitle(), mGroupShareBean.getSharelink(), wxURL);
        }
    }

    @Override
    public void ongetGroupShareDataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
    }

    @Override
    public void confirmReceiptSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void confirmReceiptError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onGroupRefundRequestSuccess(Object object) {
        Refund_Data refund = (Refund_Data) object;
        Intent intent2 = new Intent(getActivity(), RefundRequestActivity2.class);
        intent2.putExtra("data", refund);
        intent2.putExtra("Orderid",mMyGroupingBeans.get(position).getOid());
        intent2.putExtra("status","1");
        startActivity(intent2);
    }

    @Override
    public void onGroupRefundRequestError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
